var Visit = function() {

    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var detail_url = $('.detail_url').val();
    var redirect_url = $('.redirect_url').val();


    var initTable = function() {
        var table = $('#data-table');
        if(table.length > 0){
            table.dataTable({
                "processing": true,
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": true,
                "columns": [
                    {"data": "p_name"},
                    {"data": "sex"},
                    {"data": "identityNumber"},
                    {"data": "p_phone"},
                    {"data": "location"},
                    {"data": "address"},
                    {"data": "number"},
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '<button type="button" class="btn btn-danger delete-btn">删除</button>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [2, "desc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 1, 5, 7]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){

                },
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 置顶
        table.on('click', '.dotop-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);
            var isTop = $(this).data('value');

            event.preventDefault();
            var url = setTop_url;
            var data = {
                'id':id,
                'isTop':isTop
            };
            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                dataType : 'json',
                success: function (data) {
                    layer.msg(data.msg);
                    if(data.code == 1){
                        //table.DataTable().ajax.reload();
                        table.DataTable().draw(false);
                    }
                }
            });
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var tableSearch = function(table, params) {
        table.DataTable().search(JSON.stringify(params)).draw();
    };


    return {
        init: function() {
            initTable();

            this.onEvent();
        },

        onEvent : function(){
            /*$('#download_template').on('click', function(){
                var url = $(this).data('url');
                console.log(url);
                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });*/

            // 批量导入
            $('#import_csv').on('click', function(){
                var csv_file = $('input[name=csv_file]').val();
                var point = csv_file.lastIndexOf(".");

                var type = csv_file.substr(point);
                type = type.toLowerCase();
                if(type != ".csv" && type != ".xls" && type != ".xlsx"){
                    layer.msg('请选择csv, xls, xlsx文件');
                    return false;
                }

                var url = $('#import_form').attr('action');
                var data = new FormData();
                var csv_file = document.getElementById('csv_file').files[0];
                data.append('csv_file', csv_file);

                layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    //dataType : 'json',
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        layer.closeAll('loading'); // 关闭loading
                        layer.msg(data.msg);
                        if(data.status == 1){
                            window.location.reload();
                        }
                    }
                });
                return false;
            });

            // 批量导出
            $('#export_csv').on('click', function(){
                var url = $(this).data('url');

                var name = $('#searchForm').find('input[name=p_name]').val();

                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '<input name="p_name" value="'+name+'" >';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });
        }
    };

}();

$(function() {
    Visit.init();
});

